package cn.itcast.mq.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class SpringRabbitListener {

    @RabbitListener(queues = "simple.queue")
    public void listenSimpleQueue(String msg) {
        System.out.println("消费者接收到simple.queue的消息：【" + msg + "】");
    }

    //消息异常处理
    /*@RabbitListener(queues = "simple.queue")
    public void listenSimpleQueue2(String msg) {
        log.info("消费者接收到simple.queue的消息：【{}】", msg);
        // 模拟异常
        System.out.println(1 / 0);
        log.debug("消息处理完成！");
    }*/

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "error.queue"),
            exchange = @Exchange(name = "error.direct"),
            key = {"error.queue"}
    ))
    public void listenErrorQueue(String msg) {
        log.info("消费者接收到error.queue的消息：【{}】", msg);

        /// TODO:可以根据需要存入数据库，人工处理
    }

    /**
     * 定义死信交换机和死信队列
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "dl.ttl.queue", durable = "true"),
            exchange = @Exchange(name = "dl.ttl.exchange"),
            key = {"dl"}
    ))
    public void deadQueue(String msg) {
        log.info("消费者接收到dl.ttl.queue的消息：【{}】", msg);
    }

    // 声明DelayExchange交换机
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "delay.queue", durable = "true"),
            exchange = @Exchange(name = "delay.direct", delayed = "true"),
            key = {"delay"}
    ))
    public void listenDelayQueue(String msg) {
        log.info("接收到delay.queue的延迟消息：{}", msg);
    }

    /**
     * 定义惰性队列
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "lazy.queue",
                    arguments =@Argument(name = "x-queue-mode", value = "lazy")),
            exchange = @Exchange(name = "lazy.exchange"),
            key = {"lazy"}
    ))
    public void listenLazyQueue(String msg) {
        log.info("消费者接收到lazy.queue的消息：【{}】", msg);
    }
}
